include mk.def

# 用法
# 构建网关镜像 make dockerapi SVC=网关服务名
# 构建基础镜像 make docker SVC=基础服务名

# 构建基础服务
docker: start build copy-configs docker-build upload-image clean
	@echo "${COLOR_GREEN}All steps (start build copy-configs docker-build upload-image clean) complete.${COLOR_NC}"

# 构建网关服务
dockerapi: start swag build-api copy-configs docker-build upload-image clean
	@echo "${COLOR_GREEN}All steps (start swag build-api copy-configs docker-build upload-image clean) complete.${COLOR_NC}"

# 开始
start:
	@echo "${COLOR_YELLOW}Start build ${COLOR_NC}$(SERVICE_NAME) ${COLOR_YELLOW}service, please wait a few seconds.${COLOR_NC}"

# swag init
# 其中的 2>/dev/null 是将标准错误输出至`/dev/null`，以此隐藏警告信息。但这里后续可能还需要修改
swag:
	@echo "${COLOR_LIGHT_BLUE}Building swag docs.${COLOR_NC}"
	cd ../../internal/services/gate/$(SVC) && \
	swag init --parseDependency --parseInternal -g main.go -o docs 2>/dev/null && \
	cd - >/dev/null
	@echo "build finish."

# 编译服务
build:
	@echo "${COLOR_LIGHT_BLUE}Go building $(SERVICE_NAME).${COLOR_NC}"
	go env -w GOOS=linux
	go build -o app ../../internal/services/base/$(SERVICE_NAME)/*.go
	go env -w GOOS=$(OS)
	@echo "Build $(SERVICE_NAME) finish."

# 编译服务
build-api:
	@echo "${COLOR_LIGHT_BLUE}Go building $(SERVICE_NAME).${COLOR_NC}"
	go env -w GOOS=linux
	go build -o app ../../internal/services/gate/$(SERVICE_NAME)/*.go
	go env -w GOOS=$(OS)
	@echo "Build $(SERVICE_NAME) finish."

copy-configs:
	@echo "${COLOR_PURPLE}Copying configs to Dockerfile directory.${COLOR_NC}"
	cp ../../internal/config/*.yaml ./configs/
	@echo "Copy configs finish."

# 打包镜像
docker-build:
	@echo "${COLOR_LIGHT_BLUE}Building docker image $(DOCKER_IMAGE)${COLOR_NC}"
	docker build -t $(DOCKER_IMAGE) -f ./Dockerfile .
	@echo "Build $(DOCKER_IMAGE) finish."

# 上传镜像到服务器
upload-image:
	@echo "${COLOR_CYAN}Uploading docker image.${COLOR_NC}"
# 检查服务器上是否已存在同名镜像
	@if sshpass -p $(ORIGIN_SERVER_PWD) ssh $(ORIGIN_SERVER) docker inspect $(DOCKER_IMAGE) &>/dev/null; then \
		echo "Deleting existing Docker image on server."; \
		sshpass -p $(ORIGIN_SERVER_PWD) ssh $(ORIGIN_SERVER) docker rmi -f $(DOCKER_IMAGE); \
	fi
# 上传 Docker 镜像到服务器
	docker save $(DOCKER_IMAGE) | sshpass -p $(ORIGIN_SERVER_PWD) ssh $(ORIGIN_SERVER) 'docker load'
	@echo "Upload docker image finish."

# 部署服务到服务器
deploy:
	@echo "${COLOR_CYAN}Deploying image.${COLOR_NC}"
#	@sshpass -p $(ORIGIN_SERVER_PWD) ssh $(ORIGIN_SERVER) 'docker stop $(SERVICE_NAME) && docker rm $(SERVICE_NAME) && docker run -d --name $(SERVICE_NAME) $(DOCKER_IMAGE)'
#	docker run -d $(DOCKER_IMAGE) | sshpass -p $(ORIGIN_SERVER_PWD) ssh $(ORIGIN_SERVER) 'docker run'
	@sshpass -p $(ORIGIN_SERVER_PWD) ssh $(ORIGIN_SERVER) 'docker run -d --name $(SERVICE_NAME) $(DOCKER_IMAGE)'
	@echo "Deploy image finish."

# 清理本地临时生成的文件
clean:
	@echo "${COLOR_YELLOW}Deleting building files.${COLOR_NC}"
	#docker rmi $(DOCKER_IMAGE)
	rm app
	rm ./configs/*.yaml
	@echo "Delete building files finish."